using Digitalmes.Infrastructure.Unique;
using Yitter.IdGenerator;

namespace Digitalmes.Infrastructure;

public static class UniqueIdGeneratorSetup
{
    /// <summary>
    /// 注册 Id 生成器。
    /// </summary>
    /// <param name="services"></param>
    /// <returns></returns>
    public static IServiceCollection AddUniqueIdGeneratorSetup(this IServiceCollection services, IConfiguration configuration, string name = "IdGenerator")
    {
        var config = configuration.GetSection(name).Get<IdGeneratorConfig>();
        ushort workerId = config?.WorkerId ?? 1;

        // 雪花Id
        // JavaScript Number 整数允许最大值 Number.MAX_SAFE_INTEGER，即 2^53-1 = 9007199254740991
        YitIdHelper.SetIdGenerator(new IdGeneratorOptions
        {
            WorkerId = workerId, // 机器码，全局唯一（不同服务必须设定不同）
            WorkerIdBitLength = 6, // 机器码位长，默认值6，取值范围 [1, 19]
            SeqBitLength = 6, // 序列数位长，默认值6，取值范围 [3, 21]（建议不小于4，值越大性能越高、Id位数也更长）
        });

        services.AddSingleton<IUniqueIdGenerator, UniqueIdGenerator>();

        return services;
    }
}
